package cn.mineserv.video.videoordersystem.controller;

import cn.mineserv.video.videoordersystem.utils.AESDESEncryptUtil;
import cn.mineserv.video.videoordersystem.utils.CookieUtil;
import com.google.code.kaptcha.Producer;
import com.google.gson.Gson;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author 爱吃蛋白的丶圆周率
 * @company 圆周率有限公司
 */
@Controller
@RequestMapping("/code")
public class CaptchaCodeController {
    @Resource
    private Producer kaptchaProducer;

    public static final int BOUND = 255;
    public static final int COUNT_LINE = 5;

    @RequestMapping(value = "/getCode",method = RequestMethod.GET)
    public void getCode(ModelMap map, HttpServletRequest request, HttpServletResponse response, HttpSession session){
        /*//创建对象 在内存中画图
        int width = 100;
        int height = 50;
        int length = 4;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        //美化图片
        Graphics graphics = image.getGraphics();
        Random random = new Random();
        int r = 255;
        int g = 255;
        int b = 255;
        graphics.setColor(new Color(r, g, b));
        graphics.fillRect(0, 0, width, height);

        r = random.nextInt(BOUND);
        g = random.nextInt(BOUND);
        b = random.nextInt(BOUND);
        graphics.setColor(new Color(r, g, b));
        graphics.drawRect(0, 0, width - 1, height - 1);

        String code = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";

        StringBuilder codeValue = new StringBuilder();
        for (int i = 0; i < length; i++) {
            r = random.nextInt(BOUND);
            g = random.nextInt(BOUND);
            b = random.nextInt(BOUND);
            graphics.setColor(new Color(r, g, b));
            int index = random.nextInt(code.length());
            String str = code.charAt(index) + "";
            codeValue.append(code.charAt(index));
            graphics.setFont(new Font("Consolas", Font.BOLD, 28));
            graphics.drawString(str, 5 + (width / length) * i, height / 3 + 17);
        }*/
//        session.setAttribute("checkcode", codeValue.toString());
        // 创建一个 cookie对象
//        Cookie cookie = new Cookie("token", MD5Encoder.encode(codeValue.toString().toLowerCase().getBytes(StandardCharsets.UTF_8)).toLowerCase());
//        CookieUtil.setValue(response,"token", AESDESEncryptUtil.encryptString(codeValue.toString(), AESDESEncryptUtil.SYMMETRY_ENCRYPT.AES));
        //将cookie对象加入response响应
//        response.addCookie(cookie);

        /*for (int i = 0; i < COUNT_LINE; i++) {
            r = random.nextInt(BOUND);
            g = random.nextInt(BOUND);
            b = random.nextInt(BOUND);
            graphics.setColor(new Color(r, g, b));
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);

            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);
        }*/


        String text = kaptchaProducer.createText();
        CookieUtil.setValue(response,"ticket", AESDESEncryptUtil.encryptString(text, AESDESEncryptUtil.SYMMETRY_ENCRYPT.AES));
        BufferedImage image = kaptchaProducer.createImage(text);

        //图片输出到页面
        try {
            ImageIO.write(image, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/codeVerify",method = RequestMethod.POST)
    public void codeVerify(HttpServletRequest request, HttpServletResponse response, HttpSession session,@CookieValue(name = "ticket",
            defaultValue = "1234") String currentCode){
        System.out.println("currentCode12312313123 = " + currentCode);
        // , Model model
        // , ModelMap map
        // , ModelAndView modelAndView
        // , HttpSession session
        // , HttpServletRequest request
        // , HttpServletResponse response
        response.setCharacterEncoding("UTF-8");
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("text/json");
//        String currentCode = (String) session.getAttribute("checkcode");
        // System.out.println("currentCode:" + currentCode);
        String type = request.getParameter("type");

        String userCode = "";
        if ("login".equals(type)) {
            userCode = request.getParameter("login_checkcode");
        } else if ("register".equals(type)) {
            userCode = request.getParameter("register_checkcode");
        }
        // System.out.println("userCode:" + userCode);
        boolean isRight = userCode.equalsIgnoreCase(AESDESEncryptUtil.decryptString(currentCode, AESDESEncryptUtil.SYMMETRY_ENCRYPT.AES));
        Gson json = new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("isRight", isRight);
        map.put("userCode", userCode);
        String toJson = json.toJson(map);
        try {
            response.getWriter().print(toJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
